package com.sinosoft.web.common.converter;

import cn.com.sinux.spring.utils.DateUtils;
import cn.com.sinux.spring.utils.ValidatorUtils;;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.util.Date;

//省略import
public class StringToDateConverter implements Converter<String, Date> {

    private String[] formats;

    public StringToDateConverter(String[] formats) {
        this.formats = formats;
    }

    public Date convert(String source) {
        if (!StringUtils.hasLength(source)) {
            //①如果source为空 返回null
            return null;
        }
        try {
            return ValidatorUtils.isDateNumber(source) ? new Date(Long.parseLong(source)) : DateUtils.parseDate(source, formats);
        } catch (ParseException parseException) {
            throw new IllegalArgumentException(String.format("类型转换失败，需要格式[yyyy-mm-dd hh:mm:ss]，但格式是[%s]", source));
        }
    }
}
